package com.ly.demo.reference;

import java.lang.ref.WeakReference;

/**
 * @author liuyang
 * @des
 * @Version 1.0
 * @Date: 06/07/2021 15:37
 */
public class WeakReferenceTest {
    public static void main(String[] args) {

        Car car = new Car(22000, "silver");
        WeakReference<Car> weakCar = new WeakReference<Car>(car);

        int i = 0;
        while (true) {
            if (weakCar.get() != null) {
                i++;
                System.out.println("car==== " + car);
                System.out.println("Object is alive for " + i + " loops - " + weakCar);
            } else {
                System.out.println("Object has been collected.");
                break;
            }
        }
    }
    //在上例中, 程序运行一段时间后, 程序打印出”Object has been collected.” 说明, weak reference指向的对象的被回收了.
    //
    //如果要想打出的是
    //Object is alive for “+i+” loops - “+weakCar
    //
    //那么只要在这句话前面加上
    //System.out.println(“car==== “+car);
    //因为在此强引用了car对象

}
